package com.zhxy.util.message;

import java.nio.ByteBuffer;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageCodecDecoder extends CumulativeProtocolDecoder {
	
	private static final Logger logger = LoggerFactory.getLogger(MessageCodecDecoder.class);

	private MessageCodec codec;

	public MessageCodec getCodec() {
		return codec;
	}

	public void setCodec(MessageCodec codec) {
		this.codec = codec;
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {

		ByteBuffer buf = in.buf();
		buf.mark();
		Object message = codec.decode(buf);
		if (message == null) {
			buf.reset();
			return false;
		}
		
		out.write(message);
		
		logger.debug("decode:{}", message);
		return true;
	}
}
